function data = SK6_Read( address )
% SHAKE SK6 Matlab Driver v1.00, (c) 2010 SAMH Engineering Services
%
% function data = SK6_Read( address )
% This function reads the data in configuration register <address> 
% on the SK6. 
% <address> is the address to write to as a 4 digit hex string
% Data is returned as an 32 bit signed integer ( int32 )
% and has a nominal valid range of 0 to 255 ( 0x00 to 0xFF )
% The read is only transmitted if the CTS line is active
% If CTS is inactive or there is no response within the timeout
% of 3 seconds then a value of -1 is returned.
%
% Example: To read the acceleration data rate
% Rate = SK6_Read( '0008' );


% the serial port that is used is a global variable
global port

% open the sensor ID structure
IDs = SK6_Get_Sensor_IDs();

attempts = 5; % try to read 5 times before failure
header = strcat( '$REA,' , address , ',' , data );
data = int32( -1 ); % return failure by default
timeout = 3; % set the timeout for a response to 3 seconds ( it can be this long if a bluetooth connection is poor )

% clear the receive buffer of previous ACK packets
ack_packets = SK6_Data_Samples_Available( IDs.Ack );
SK6_Get_Sensor_Data( IDs.Ack , ack_packets );


% try the write a few times in case
while attempts > 0
  
  % make sure that CTS is active before attempting the write
  if strcmp( port.PinStatus.ClearToSend , 'off')
    fprintf( 2,'SK6 CTS is active, stalling for 20mS\n' );
  else
    % send the $WRI packet to the SK6
    fprintf( port , header );
    
    % wait for the $ACK into the COM port buffer with timeout
    tic;
    while ( SK6_Data_Samples_Available( IDs.Ack ) == 0 ) && ( toc < timeout )
      pause(0.005)% sleep to prevent busy waiting processor loading
    end
    
    % read the $ACK packet
    ack_packet_data = SK6_Get_Sensor_Data( IDs.Ack , 1 );
    
    % check that the $ACK packet has valid address and value fields
    if ( ack_packet_data(1) == int32(hex2dec( address )) )&&...  % the address field
        ( ack_packet_data(3) == 1 )  % the value (ACK / NAK) field, 1 == ACK, 0 == NAK
      % $ACK returned succesfully
      data = int32( ack_packet_data(2) );
      break;
    end
    
  end
  attempts = attempts - 1;
  pause(0.02); % SK6 not ready to receive, wait 20ms before trying again
end

if data == -1
  err_string = strcat( 'SK6 read failed on address 0x', address , '\n' );
  fprintf( 1, err_string );
end

end %function SK6_Read(address,data)

